<?php


namespace app\common;


use think\db\exception\DbException;
use think\Model;

class BaseModel extends Model
{
    /**
     * 生成查询条件和分页条件
     * @param array $param 校验通过的参数
     * @param array $condition 条件表达式
     * @param array $extra 额外查询条件
     * @param array $paramKey 添加允许参与生成查询表达式字段
     * @return array
     */
    private function makePaginate(array $param = [], array $condition = [], array $extra = [], $paramKey= [])
    {
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;
        unset($param['page']);
        unset($param['limit']);

        $new_condition = [];
        $index = 0;
        foreach ($param as $key => $value) {
            $condition_str = $condition[$key];
            $new_condition[$index] = $condition_str;
            $index++;
        }
        foreach ($paramKey as $key) {
            $condition_str = $condition[$key];
            $new_condition[$index] = $condition_str;
            $index++;
        }
        if (!empty($extra)) {
            array_push($new_condition, $extra);
        }
        return array($new_condition, $page, $limit);
    }

    /**
     * 需要分页的查询
     * @param array $param 校验通过的参数
     * @param array $condition 条件表达式
     * @param array $hidden 要隐藏的字段
     * @param array $paramKey 添加允许参与生成查询表达式字段
     * @return array
     * @throws DbException
     */
    public function toPaginate(array $param = [], array $condition = [], array $hidden = [], array $paramKey = []): array
    {
        [$new_condition, $page, $limit] = $this->makePaginate($param, $condition, [], $paramKey);
        $arr = $this->where($new_condition)
            ->hidden($hidden)
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->toArray();
        $lists = $arr['data'];
        unset($arr['data']);
        $arr['lists'] = $lists;
        return $arr;
    }

    /**
     * 关联后的分页查询
     * @param array $with 关联条件
     * @param array $param 校验通过的参数
     * @param array $condition 条件表达式
     * @param array $hidden 隐藏的字段
     * @param array $extra 额外的查询条件
     * @param array $order 排序
     * @param array $paramKey 添加允许参与生成查询表达式字段
     * @return array
     * @throws DbException
     */
    public function withPaginate(array $with, array $param = [], array $condition = [], array $hidden = [],
                                 array $extra = [], array $order = [], array $paramKey = [])
    {
        [$new_condition, $page, $limit] = $this->makePaginate($param, $condition, $extra, $paramKey);
        $arr = $this->with($with)
            ->where($new_condition)
            ->order($order)
            ->hidden($hidden)
            ->paginate(['list_rows' => $limit, 'page' => $page])
            ->toArray();
        $lists = $arr['data'];
        unset($arr['data']);
        $arr['lists'] = $lists;
        return $arr;
    }
}